package com.zzt.blog.common.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description
 * User: panda
 * Date: 2025-04-30
 * Time: 15:58
 */
public class SecurityUtil {
    /**
     * 加密
     * md5(salt+明文)
     * @param password 密码
     * @return 盐值 + md5(盐值+明文)
     */
    public static String encrypt(String password){
        String salt = UUID.randomUUID().toString().replace("-", "");
        String securityPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        return salt + securityPassword;
    }

    /**
     * 验证
     * 数据库中存储的是 盐值 + md5(盐值+明文)
     * @return
     */
    public static boolean verify(String inputPassword, String sqlPassword){
        if(!StringUtils.hasLength(inputPassword)){
            return false;
        }
        if(sqlPassword == null || sqlPassword.length() != 64){
            return false;
        }
        String salt = sqlPassword.substring(0,32);
        String securityPassword = DigestUtils.md5DigestAsHex((salt+inputPassword).getBytes(StandardCharsets.UTF_8));
        return sqlPassword.equals(salt + securityPassword);
    }

    public static void main(String[] args) {
        String encrypt = encrypt("123456");
        System.out.println(encrypt);
        boolean verify = verify("12346",encrypt);
        System.out.println(verify);
    }
}
